const db = require("../config/mysql");

const LogsModel = {
  // 获取所有日志（分页、筛选）
  getLogs: async (filters = {}, page = 1, limit = 10) => {
    let sql = `
            SELECT 
                sl.id,
                sl.op_type,
                sl.op_desc,
                sl.ip,
                sl.user_id,
                sl.create_time,
                sl.client_type,
                u.user_name
            FROM sys_logs sl
            LEFT JOIN user u ON sl.user_id = u.user_id
            WHERE 1=1
        `;
    const params = [];

    if (filters.op_type) {
      sql += ` AND sl.op_type = ?`;
      params.push(filters.op_type);
    }

    if (filters.user_id) {
      sql += ` AND sl.user_id = ?`;
      params.push(parseInt(filters.user_id));
    }

    if (filters.op_desc) {
      sql += ` AND sl.op_desc LIKE ?`;
      params.push(`%${filters.op_desc}%`);
    }

    if (filters.client_type) {
      sql += ` AND sl.client_type = ?`;
      params.push(filters.client_type);
    }

    if (filters.user_name) {
      sql += ` AND u.user_name LIKE ?`;
      params.push(`%${filters.user_name}%`);
    }

    if (filters.start_time && filters.end_time) {
      sql += ` AND sl.create_time BETWEEN ? AND ?`;
      params.push(filters.start_time, filters.end_time);
    } else if (filters.create_time) {
      sql += ` AND sl.create_time = ?`;
      params.push(filters.create_time);
    }

    // 分页查询
    sql += ` ORDER BY sl.create_time DESC LIMIT ?, ?`;
    params.push((page - 1) * limit, parseInt(limit));

    let countSql = `
            SELECT COUNT(*) AS total 
            FROM sys_logs sl
            LEFT JOIN user u ON sl.user_id = u.user_id
            WHERE 1=1
        `;
    const countParams = [];

    if (filters.op_type) {
      countSql += ` AND sl.op_type = ?`;
      countParams.push(filters.op_type);
    }

    if (filters.user_id) {
      countSql += ` AND sl.user_id = ?`;
      countParams.push(parseInt(filters.user_id));
    }

    if (filters.op_desc) {
      countSql += ` AND sl.op_desc LIKE ?`;
      countParams.push(`%${filters.op_desc}%`);
    }

    if (filters.client_type) {
      countSql += ` AND sl.client_type = ?`;
      countParams.push(filters.client_type);
    }

    if (filters.user_name) {
      countSql += ` AND u.user_name LIKE ?`;
      countParams.push(`%${filters.user_name}%`);
    }

    if (filters.start_time && filters.end_time) {
      countSql += ` AND sl.create_time BETWEEN ? AND ?`;
      countParams.push(filters.start_time, filters.end_time);
    } else if (filters.create_time) {
      countSql += ` AND sl.create_time = ?`;
      countParams.push(filters.create_time);
    }

    const [totalResult] = await db.query(countSql, countParams);
    const [rows] = await db.query(sql, params);

    return {
      total: totalResult[0].total,
      rows: rows,
    };
  },

  // 删除日志
  deleteById: async (id) => {
    const sql = "DELETE FROM sys_logs WHERE id = ?";
    const [res] = await db.query(sql, [id]);
    return res.affectedRows; // 返回实际删除行数
  },

  // 新增日志
  createLog: async (logData) => {
    const { op_type, op_desc, ip, user_id, client_type } = logData;

    const sql = `
            INSERT INTO sys_logs 
            (op_type, op_desc, ip, user_id, create_time, client_type)
            VALUES (?, ?, ?, ?, NOW(), ?)
        `;
    const params = [
      op_type,
      op_desc,
      ip,
      user_id || null, // 允许为空
      client_type || "OTHER", // 默认值
    ];

    const [result] = await db.query(sql, params);
    return result.insertId; // 返回新插入的 ID
  },
};

module.exports = LogsModel;
